import React, { useState, useRef } from 'react'
import { 
  List, 
  NavBar,
  Button,
  Dialog,
  Toast
} from 'antd-mobile'
import {
  LeftOutline,
  RightOutline,
  UserOutline,
  CameraOutline,
  PictureOutline
} from 'antd-mobile-icons'
import { useNavigate } from 'react-router-dom'
import { getAuthToken, getUserId, getUserRole, clearLoginStatus } from '../../utils/auth'
import './settings.css'

function Settings() {
  const navigate = useNavigate()
  
  // 头像状态管理
  const [avatar, setAvatar] = useState<string>('')
  const [showAvatarModal, setShowAvatarModal] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  // 页面加载时读取本地存储的头像
  React.useEffect(() => {
    loadAvatarFromLocal()
  }, [])

  // 处理返回
  const handleBack = () => {
    navigate(-1)
  }

  // 处理退出登录
  const handleLogout = () => {
    if (confirm('确定要退出登录吗？')) {
      // 清除登录状态和token
      clearLoginStatus()
      // 跳转到登录页
      navigate('/login')
    }
  }
  // 处理头像选择
  const handleAvatarClick = () => {
    setShowAvatarModal(true)
  }
  // 处理拍照
  const handleTakePhoto = () => {
    setShowAvatarModal(false)
    // 这里可以调用相机API
    Toast.show('拍照功能开发中...')
  }
  // 处理从相册选择
  const handleChooseFromAlbum = () => {
    setShowAvatarModal(false)
    if (fileInputRef.current) {
      fileInputRef.current.click()
    }
  }
  // 处理文件选择
  const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0]
    if (file) {
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        Toast.show('请选择图片文件')
        return
      }
      // 检查文件大小（5MB限制）
      if (file.size > 5 * 1024 * 1024) {
        Toast.show('图片大小不能超过5MB')
        return
      }
      // 压缩图片
      compressImage(file, (compressedDataUrl) => {
        setAvatar(compressedDataUrl)
        // 保存到本地存储
        saveAvatarToLocal(compressedDataUrl)
        Toast.show('头像更新成功！')
        
        // 清空文件输入，允许重复选择同一文件
        if (fileInputRef.current) {
          fileInputRef.current.value = ''
        }
      })
    }
  }
  // 压缩图片
  const compressImage = (file: File, callback: (dataUrl: string) => void) => {
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    const img = new Image()
    img.onload = () => {
      // 设置最大尺寸
      const maxSize = 200
      let { width, height } = img
      // 计算缩放比例
      if (width > height) {
        if (width > maxSize) {
          height = (height * maxSize) / width
          width = maxSize
        }
      } else {
        if (height > maxSize) {
          width = (width * maxSize) / height
          height = maxSize
        }
      }
      // 设置canvas尺寸
      canvas.width = width
      canvas.height = height 
      // 绘制图片
      ctx?.drawImage(img, 0, 0, width, height)
      // 转换为base64，设置质量为0.8
      const dataUrl = canvas.toDataURL('image/jpeg', 0.8)
      callback(dataUrl)
    }
    img.src = URL.createObjectURL(file)
  }
  // 保存头像到本地存储
  const saveAvatarToLocal = (avatarData: string) => {
    try {
      // 保存头像数据
      localStorage.setItem('userAvatar', avatarData)
      // 保存头像信息
      const avatarInfo = {
        data: avatarData,
        timestamp: new Date().toISOString(),
        size: avatarData.length
      }
      localStorage.setItem('userAvatarInfo', JSON.stringify(avatarInfo))
      console.log('头像已保存到本地存储')
    } catch (error) {
      console.error('保存头像失败:', error)
      Toast.show('保存头像失败，请重试')
    }
  }
  // 从本地存储读取头像
  const loadAvatarFromLocal = () => {
    try {
      const savedAvatar = localStorage.getItem('userAvatar')
      if (savedAvatar) {
        setAvatar(savedAvatar)
        console.log('头像已从本地存储加载')
      }
    } catch (error) {
      console.error('加载头像失败:', error)
      Toast.show('加载头像失败')
    }
  }
  // 清除本地存储的头像
  const clearAvatarFromLocal = () => {
    try {
      localStorage.removeItem('userAvatar')
      localStorage.removeItem('userAvatarInfo')
      setAvatar('')
      console.log('头像已从本地存储清除')
      Toast.show('头像已清除')
    } catch (error) {
      console.error('清除头像失败:', error)
      Toast.show('清除头像失败')
    }
  }
  // 获取头像存储信息
  const getAvatarStorageInfo = () => {
    try {
      const avatarInfo = localStorage.getItem('userAvatarInfo')
      if (avatarInfo) {
        const info = JSON.parse(avatarInfo)
        return {
          timestamp: new Date(info.timestamp).toLocaleString(),
          size: (info.size / 1024).toFixed(2) + ' KB'
        }
      }
      return null
    } catch (error) {
      console.error('获取头像信息失败:', error)
      return null
    }
  }
  // 处理设置项点击
  const handleSettingClick = (type: string) => {
    switch (type) {
      case 'avatar':
        handleAvatarClick()
        break
      case 'nickname':
        alert('昵称设置功能')
        break
      case 'account':
        alert('账号设置功能')
        break
      case 'privacy':
        alert('隐私设置功能')
        break
      default:
        break
    }
  }
  return (
    <div className="settings-container">
      {/* 顶部导航栏 */}
      <NavBar 
        onBack={handleBack}
        className="settings-header"
        backArrow={<LeftOutline />}
      >
        设置
      </NavBar>
      {/* 用户资料设置 */}
      <div className="settings-section">
        <div className="settings-section-title">用户资料</div>
        <List>
          <List.Item
            prefix={
              <div className="avatar-preview" onClick={() => handleSettingClick('avatar')}>
                {avatar ? (
                  <img src={avatar} alt="头像" className="avatar-image" />
                ) : (
                  <UserOutline style={{ color: '#1890ff', fontSize: '20px' }} />
                )}
              </div>
            }
            arrow={<RightOutline />}
            onClick={() => handleSettingClick('avatar')}
            className="settings-item"
          >
            <div>
              <div>头像</div>
              {avatar && (
                <div style={{ 
                  fontSize: '12px', 
                  color: '#999',
                  marginTop: '2px'
                }}>
                  {(() => {
                    const info = getAvatarStorageInfo()
                    return info ? `已保存到本地 (${info.size})` : '已保存到本地'
                  })()}
                </div>
              )}
            </div>
          </List.Item>
          <List.Item
            arrow={<RightOutline />}
            onClick={() => handleSettingClick('nickname')}
            className="settings-item"
          >
            昵称
          </List.Item>
          <List.Item
            arrow={<RightOutline />}
            onClick={() => handleSettingClick('account')}
            className="settings-item"
          >
            账号设置
          </List.Item>
        </List>
      </div>

      {/* 通用设置 */}
      <div className="settings-section">
        <div className="settings-section-title">通用设置</div>
        <List>
          <List.Item
            arrow={<RightOutline />}
            onClick={() => handleSettingClick('privacy')}
            className="settings-item"
          >
            隐私
          </List.Item>
          <List.Item className="settings-item">
            <span>当前版本</span>
            <span style={{ color: '#666' }}>4.0.0</span>
          </List.Item>
        </List>
      </div>

      {/* 头像存储信息 */}
      {avatar && (
        <div className="avatar-info-section">
          <div className="avatar-info-title">头像存储信息</div>
          <div className="avatar-info-content">
            {(() => {
              const info = getAvatarStorageInfo()
              return info ? (
                <div>
                  <div>存储时间: {info.timestamp}</div>
                  <div>文件大小: {info.size}</div>
                  <div>存储位置: 本地浏览器存储</div>
                </div>
              ) : (
                <div>存储信息获取失败</div>
              )
            })()}
          </div>
        </div>
      )}
      {/* Token信息 */}
      <div className="settings-section">
        <div className="settings-section-title">认证信息</div>
        <List>
          <List.Item className="settings-item">
            <span>用户ID</span>
            <span style={{ color: '#666' }}>{getUserId() || '未获取'}</span>
          </List.Item>
          <List.Item className="settings-item">
            <span>用户角色</span>
            <span style={{ color: '#666' }}>{getUserRole() || '未获取'}</span>
          </List.Item>
          <List.Item className="settings-item">
            <span>Token状态</span>
            <span style={{ color: getAuthToken() ? '#52c41a' : '#ff4d4f' }}>
              {getAuthToken() ? '有效' : '无效'}
            </span>
          </List.Item>
          <List.Item className="settings-item">
            <span>Token预览</span>
            <span style={{ 
              color: '#666', 
              fontSize: '12px',
              maxWidth: '150px',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap'
            }}>
              {getAuthToken() ? `${getAuthToken()?.substring(0, 20)}...` : '无'}
            </span>
          </List.Item>
        </List>
      </div>
      {/* 退出登录按钮 */}
      <div className="logout-section">
        <Button
          block
          className="logout-button"
          onClick={handleLogout}
        >
          退出登录
        </Button>
      </div>
      {/* 头像选择模态框 */}
      <Dialog
        visible={showAvatarModal}
        title="选择头像"
        content={
          <div className="avatar-options">
            <div className="avatar-option" onClick={handleTakePhoto}>
              <CameraOutline style={{ fontSize: '24px', color: '#1890ff' }} />
              <span>拍照</span>
            </div>
            <div className="avatar-option" onClick={handleChooseFromAlbum}>
              <PictureOutline style={{ fontSize: '24px', color: '#1890ff' }} />
              <span>从相册选择</span>
            </div>
            {avatar && (
              <div className="avatar-option" onClick={clearAvatarFromLocal}>
                <div style={{ 
                  fontSize: '24px', 
                  color: '#ff4d4f', 
                  width: '24px',
                  height: '24px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center'
                }}>
                  ×
                </div>
                <span style={{ color: '#ff4d4f' }}>清除头像</span>
              </div>
            )}
          </div>
        }
        closeOnAction
        onClose={() => setShowAvatarModal(false)}
        actions={[
          {
            key: 'cancel',
            text: '取消',
            onClick: () => setShowAvatarModal(false)
          }
        ]}
      />
      {/* 隐藏的文件输入 */}
      <input
        ref={fileInputRef}
        type="file"
        accept="image/*"
        style={{ display: 'none' }}
        onChange={handleFileSelect}
      />
    </div>
  )
}
export default Settings
